package csc.com.listeners;

import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import csc.com.util.DBConnectionManager;

@WebListener
public class AppContextListener implements ServletContextListener {
	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		// TODO Auto-generated method stub
		ServletContext context = servletContextEvent.getServletContext();
		
		// Initialize DB connection
		String dbURL = context.getInitParameter("dbURL");
		String dbUser = context.getInitParameter("dbUser");
		String dbPass = context.getInitParameter("dbPassword");
		
		try {
			DBConnectionManager dbConection = new DBConnectionManager(dbURL, dbUser, dbPass);
			context.setAttribute("DBConnection", dbConection.getConnection());
			System.out.println("DB Connection initialized successfully");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}	

	@Override
	public void contextDestroyed(ServletContextEvent servletContextEvent) {
		// TODO Auto-generated method stub
		   Connection connection = (Connection) servletContextEvent.getServletContext().getAttribute("DBConnection");
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
	}
}
